<template>
  <div ref="root" class="explorer">
    <!-- mode normal -->
    <div
      v-if="mode === 'normal' && dataArr.length"
      class="explorer-normal"
    >
      <div
        v-for="(item, i) in dataArr"
        :key="item.key"
        class="explorer-normal-item"
        :class="{ active: selectedKeyArr.indexOf(item.key) !== -1 }"
        draggable
        @click="clickItem(item)"
        @dblclick="dblclickItem(item)"
      >
      <!-- @contextmenu="openAction($event, item)" -->
        <!-- 选中按钮 -->
        <img
          v-if="selection"
          class="explorer-normal-item-selected"
          src="@/assets/folder_images/icon-selected.png"
          alt=""
          @click.stop="normalToggleSelected(item)"
        >
        <!-- 图标 -->
        <!-- :src="item.type != 'image' ? typeIconMap[ item.type ] || typeIconMap['none'] : item.base64" -->
        <img
          class="explorer-normal-item-icon"
          :src="typeIconMap[ item.type ] || typeIconMap['none']"
          alt=""
        >
        <!-- 名称 -->
        <span v-if="item.isSearch == true" class="explorer-normal-item-name" style="font-size: 10px; width: 450px;" :title="getTitle(item)">
          {{ item.name || '' }} ----- {{item.filepath}}
        </span>
        <span v-else class="explorer-normal-item-name" style="font-size: 10px; width: 450px;" :title="getTitle(item)">
          {{ item.name || '' }}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'JasonVueExplorer',
  props: {
    /**
     *  文件数据，一维数组
     *  每一项数据如下:
     *    {
     *      // 唯一值
     *      key: [String, Number],
     *
     *      // 显示名称
     *      name: String,
     *
     *      // 类型
     *      type: String[folder/docx/excel/image/mp3/pdf/ppt/txt/video/zip/none]
     *
     *      // 额外数据
     *      data: Object
     *    }
     **/
    dataArr: {
      type: Array,
      default() {
        return []
      }
    },

    /**
     *  是否开启选择
     **/
    selection: {
      type: Boolean,
      default: true
    },

    /**
     *  被选中的项数据集合
     *  注意：
     *    selection 要为 true
     *    table 模式有引用地址的问题
     *    所以要保证项对象在 dataArr 中能找到并且全等
     **/
    selectedArr: {
      type: Array,
      default() {
        return []
      }
    },

    /**
     *  显示模式
     *  normal - 正常模式
     *  table  - 表格模式
     **/
    mode: {
      type: String,
      default: 'normal'
    },

    /**
     *  table 模式显示新的列
     *  normal 该 prop 无效
     *  第一列选中，第二列名字
     *  是必有的，可以考虑通过 css 的方式隐藏这两个固有列
     *  来显示纯显示
     *  {
     *    label: String,
     *    path: String,
     *    filter: Function
     *  }
     **/
    otherColumnArr: {
      type: Array
    }

    /**
     *  对于每一项的单独操作
     *  右键项即可弹出操作列表
     *  [
     *    {
     *      label: String（显示的名字）
     *      handler: Function（处理函数，参数为当前项）
     *    }
     *  ]
     **/
    // actionArr: {
    //   type: Array,
    //   default: () => {
    //     return []
    //   }
    // }
  },
  // mounted () {
  //   getData()
  // },
  data() {
    return {
      // 各个类型的图标数据
      typeIconMap: {
        doc: require('@/assets/folder_images/icon-doc.png'),
        xls: require('@/assets/folder_images/icon-xls.png'),
        folder: require('@/assets/folder_images/icon-folder.png'),
        image: require('@/assets/folder_images/icon-image.png'),
        mp3: require('@/assets/folder_images/icon-mp3.png'),
        none: require('@/assets/folder_images/icon-none.png'),
        pdf: require('@/assets/folder_images/icon-pdf.png'),
        ppt: require('@/assets/folder_images/icon-ppt.png'),
        video: require('@/assets/folder_images/icon-video.png'),
        zip: require('@/assets/folder_images/icon-zip.png'),
        rar: require('@/assets/folder_images/icon-rar.png'),
        txt: require('@/assets/folder_images/icon-txt.png'),
        json: require('@/assets/folder_images/icon-json.png')
      },
      // 显示 action
      showAction: false,
      // action 位置
      actionX: 0,
      actionY: 0
    }
  },
  computed: {
    selectedKeyArr() {
      const result = []
      this.selectedArr.forEach(item => {
        result.push(item.key)
      })
      return result
    }
  },
  watch: {
    selectedArr: {
      immediate: true,
      handler(newArr, oldArr) {
        if (
          this.mode !== 'table' ||
          this.dataArr.length === 0 ||
          JSON.stringify(newArr) === JSON.stringify(oldArr)
        ) {
          return null
        }
      }
    }
  },
  methods: {
    getTitle(item){
      if(item.isSearch){
        return item.name + '-----' + item.filepath
      }else {
        return item.name
      }

    },
    // 点击文件或者文件夹
    clickItem(item) {
      // if(item.type === 'json'|| item.type === 'folder'||)
      // {
      this.normalToggleSelected(item)
      // }
      this.$emit(
        item.type === 'folder'
          ? 'clickFolder'
          : 'clickFile',
        item
      )
    },
    // 双击文件或者文件夹
    dblclickItem(item) {
      this.$emit(
        item.type === 'folder'
          ? 'dblclickFolder'
          : 'dblclickFile',
        item
      )
    },
    // 打开操作菜单
    // openAction(e, data) {
    //   if (this.actionArr.length === 0) {
    //     return null
    //   }

    //   let target = e.target
    //   let offsetX = e.offsetX
    //   let offsetY = e.offsetY

    //   while (target !== this.$refs.root) {
    //     offsetX += target.offsetLeft
    //     offsetY += target.offsetTop
    //     target = target.offsetParent
    //   }

    //   this.showAction = true
    //   this.actionX = offsetX
    //   this.actionY = offsetY

    //   e.preventDefault()

    //   // 选中当前的项
    //   this.$emit('update:selectedArr', [data])

    //   // 点击后隐藏 action
    //   document.addEventListener('click', (() => {
    //     const handler = () => {
    //       this.showAction = false
    //       document.removeEventListener('click', handler)
    //     }

    //     return handler
    //   })())
    // },

    // normal 模式切换选中状态
    normalToggleSelected(item) {
      setTimeout(()=>{
        // if(item.type === 'folder') return null
        const arr = [...this.selectedArr]
        let i = -1

        for (let j = 0; j < arr.length; j++) {
          if (arr[j].key === item.key) {
            i = j
            break
          }
        }
        if (i === -1) {
          arr.push(item)
        } else {
          arr.splice(i, 1)
        }
        console.log(arr)
        this.$emit('update:selectedArr', arr)
      },100)
    },

    // table 模式切换选中状态（el-table 自带全选功能）
    // tableToggleSelected(arr) {
    //   this.$emit('update:selectedArr', [...arr])
    // },

    // // 根据 prop selectedArr 同步 el-table 的选中状态
    // syncElTableSelectedArr(newSelectedArr) {
    //   this.$refs.table.clearSelection()

    //   newSelectedArr.forEach(item => {
    //     this.$refs.table.toggleRowSelection(item)
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
.explorer {
  position: relative;
  color: #000;
  box-sizing: border-box;
  font-size: 14px;
  background-color: #fff;
  line-height: 1.25;

  &-normal {
    display: flex;
    flex-wrap: wrap;

    &-item {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 450px;
      border-radius: 5px;
      cursor: pointer;
      padding: 10px;

      &-selected {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 5;
        color: #4b4b4b;
        opacity: 0;
        cursor: pointer;
        width: 18px;
        margin: 5px;
      }

      &-icon {
        margin-left: 15px;
        display: block;
        height: 40px;
      }

      &-name {
        color: #8e8c8c;
        margin: 10px 10px 10px 10px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 100%;
        text-align: left;
      }

      // 鼠标移入状态
      &, &-selected {
        transition: all .15s;
      }

      &:hover {
        background-color: rgba(#000, 0.05);
      }

      &:hover &-selected {
        opacity: 0.4;
      }

      & &-selected:hover {
        opacity: 0.7;
      }

      // 选中时的状态
      &.active &-selected {
        color: #409EFF;
        opacity: 1;
      }
    }
  }

  &-table {
    font-size: inherit;

    &-name {
      display: flex;
      align-items: center;
      cursor: pointer;

      img {
        width: 30px;
        margin-right: 12px;
      }
    }

    .el-table__row {
      cursor: pointer;
    }
  }

  &-empty {
    display: block;
    margin: 0 auto;
    max-width: 240px;
  }

  &-action {
    position: absolute;
    z-index: 5;
    border-radius: 5px;
    border: 1px solid #ebeef5;
    min-width: 100px;
    background-color: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

    &-item {
      padding: 12px;

      & {
        transition: all .2s;
        cursor: pointer;
      }

      &:hover {
        background-color: rgba(#000, 0.05);
      }
    }
  }
}
</style>
